using SmartBoard.Core.Server;

namespace SmartBoard.Core.Networking.Client
{
    internal class ConnectionDataManager : IClientDataWriter
    {
        private readonly ServerMessageBuilder _serverMessageBuilder;
        
        public ConnectionDataManager()
        {
            _serverMessageBuilder = new ServerMessageBuilder();
        }

        internal void OnDataRecieved(byte[] data)
        {
            var message = _serverMessageBuilder.GetServerMessage(data);
            if(message != null)
            {
                var module = ModuleManager.GetModule(message.MessageTargetModuleId);
                if(module != null)
                {
                    module.AcceptMessage(message);
                }
                else
                {
                    // Write Error
                }
            }
        }

        public INetworkModuleManager ModuleManager
        {
            get; set;
        }

        public ClientNetworkConnection Connection
        {
            get; set;
        }

        #region IClientDataWriter Members

        public void Write(IServerMessage message)
        {
            var data = _serverMessageBuilder.GetRawBuffer(message);
            Connection.Write(data);
        }

        #endregion
    }
}